package com.library.controller;

import com.library.bean.Admin;
import com.library.bean.ReaderCard;
import com.library.bean.ReaderInfo;
import com.library.dao.AdminBorrowDao;
import com.library.service.AdminBorrowService;
import com.library.service.LoginService;
import com.library.service.ReaderCardService;
import com.library.service.ReaderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;

/*登录、注册、修改密码相关的Controller*/

@Controller
public class LoginController {

    /*LoginService对应AdminDao*/
    private LoginService loginService;
    @Autowired
    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    @Autowired
    private AdminBorrowService adminBorrowService;


    /*添加注册功能，才添加下面这三个*/
    @Autowired
    private ReaderInfoService readerInfoService;

    @Autowired
    private ReaderCardService readerCardService;

    @Autowired
    private ReaderController  readerController;

    /*访问登录界面*/
    @RequestMapping(value = {"/", "/login.html"})
    public String toLogin(HttpServletRequest request) {
        request.getSession().invalidate();
        return "index";
    }

    /*用户退出，重定向到登录界面*/
    @RequestMapping("/logout.html")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/login.html";
    }

    /*用户登录  使用ajax处理数据*/
    //请求参数会根据参数名称默认契约自动绑定到相应方法的入参中
    @RequestMapping(value = "/api/loginCheck", method = RequestMethod.POST)
    public @ResponseBody
    Object loginCheck(HttpServletRequest request) {
        long id = Long.parseLong(request.getParameter("id"));
        String passwd = request.getParameter("passwd");
        boolean isAdmin = loginService.hasMatchAdmin(id, passwd);               //管理员权限或借阅管理员权限
        boolean isReader = loginService.hasMatchReader(id, passwd);             //读者权限
        HashMap<String, String> res = new HashMap<>();
        if (isAdmin) {
            Admin admin = adminBorrowService.findAdmainBorrowById(id);
            //session把管理员对象存起来,账号没有退出前会一直存在
            request.getSession().setAttribute("admin", admin);
            res.put("stateCode", "1");
            res.put("msg", "管理员登陆成功！");
        } else if (isReader) {
            ReaderCard readerCard = loginService.findReaderCardByReaderId(id);
            //session把ReaderCard对象存起来,账号没有退出前会一直存在
            request.getSession().setAttribute("readercard", readerCard);
            res.put("stateCode", "2");
            res.put("msg", "读者登陆成功！");
        } else {
            res.put("stateCode", "0");
            res.put("msg", "账号或密码错误！");
        }
        return res;
    }
    /*管理员登录成功访问主界面*/
    @RequestMapping("/admin_main.html")
    public ModelAndView toAdminMain(HttpServletResponse response) {
        return new ModelAndView("admin_main");
    }

    /*读者登录成功访问主界面*/
    @RequestMapping("/reader_main.html")
    public ModelAndView toReaderMain(HttpServletResponse response) {
        return new ModelAndView("reader_main");
    }

    /*-------------------------------------------注册这里用到了ajax----------------------------------------------*/
    /*读者 注册账号(第一步)*/
    @RequestMapping("reader_zhuce.html")
    public ModelAndView readerInfoAdd() {
        return new ModelAndView("reader_zhuce");
    }

    /*读者 注册(第二步     ajax) 判断账号是否存在*/
    @RequestMapping(value = "/api/zhuceCheck", method = RequestMethod.POST)
    public @ResponseBody
    Object zhuceCheck(HttpServletRequest request) {
        //解决因账号存在，自动清空后传递空字符串Long.parseLong()异常
        if("".equals(request.getParameter("id"))){
            return  null;
        }
        long id = Long.parseLong(request.getParameter("id"));
        boolean exit = false;   //账号是否存在
        //和已经注册的读者账号重复
        ArrayList<ReaderInfo> allreader= readerInfoService.readerInfos();
        for (int i = 0 ; i < allreader.size(); i++){
            if(id == allreader.get(i).getReaderId()){
                exit = true;
            }
        }
        HashMap<String, String> res = new HashMap<>();
        if (!exit)
            res.put("stateCode", "1");
        if (id<9999 || id>99999 )
            res.put("stateCode", "2");
        if (id>9999 && id<=99999 &&exit)
            res.put("stateCode", "3");
        return res;
    }

    /*读者 注册(第三步)*/
    @RequestMapping("reader_zhuce_do.html")
    public String readerInfoAddDo(HttpServletRequest request,long readerId, String name, String sex, String birth, String address, String phone, String password, RedirectAttributes redirectAttributes) {

        ReaderInfo readerInfo = readerController.getReaderInfo(readerId, name, sex, birth, address, phone);
        if (readerInfoService.addReaderInfo(readerInfo) && readerCardService.addReaderCard(readerInfo, password)) {
            redirectAttributes.addFlashAttribute("succ", "读者注册成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "读者注册失败！");
        }
        return "redirect:/login.html";
    }

    /*管理员 修改密码(第一步)   问题解决2020-3-20*/
    @RequestMapping("/admin_borrow_repasswd.html")
    public ModelAndView reAdminBorrowPasswd() {
        return new ModelAndView("admin_borrow_repasswd");
    }

    /*管理员 修改密码(第二步)*/
    @RequestMapping("/admin_borrow_repasswd_do.html")
    public String reAdminBorrowPasswdDo(HttpServletRequest request, String oldPasswd, String newPasswd, String reNewPasswd, RedirectAttributes redirectAttributes) {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        long id = admin.getAdminId();
        //从数据库中获取当前借阅管理员的密码
        String password = adminBorrowService.getAdminBorrowPassword(id);
        if (password.equals(oldPasswd)) {
            if (adminBorrowService.resetAdminBorrowPassword(id, newPasswd)) {
                redirectAttributes.addFlashAttribute("succ", "密码修改成功！");
                return "redirect:/admin_borrow_repasswd.html";
            } else {
                redirectAttributes.addFlashAttribute("error", "密码修改失败！");
                return "redirect:/admin_borrow_repasswd.html";
            }
        } else {
            redirectAttributes.addFlashAttribute("error", "旧密码错误！");
            return "redirect:/admin_borrow_repasswd.html";
        }
    }

    /*读者 修改密码(第一步)*/
    @RequestMapping("/reader_repasswd.html")
    public ModelAndView reReaderPasswd() {
        return new ModelAndView("reader_repasswd");
    }

    /*读者 修改密码(第二步)*/
    @RequestMapping("/reader_repasswd_do")
    public String reReaderPasswdDo(HttpServletRequest request, String oldPasswd, String newPasswd, String reNewPasswd, RedirectAttributes redirectAttributes) {
        ReaderCard reader = (ReaderCard) request.getSession().getAttribute("readercard");
        long id = reader.getReaderId();
        String password = loginService.getReaderPassword(id);
        if (password.equals(oldPasswd)) {
            if (loginService.readerRePassword(id, newPasswd)) {
                redirectAttributes.addFlashAttribute("succ", "密码修改成功！");
                return "redirect:/reader_repasswd.html";
            } else {
                redirectAttributes.addFlashAttribute("error", "密码修改失败！");
                return "redirect:/reader_repasswd.html";
            }
        } else {
            redirectAttributes.addFlashAttribute("error", "旧密码错误！");
            return "redirect:/reader_repasswd.html";
        }
    }

    //配置404页面
    @RequestMapping("*")
    public String notFind() {
        return "404";
    }

}